package spring.cloud.tasks.tasks_manager.tasks_manager.listener;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type;
import spring.cloud.tasks.tasks_manager.tasks_manager.node.Node;
import spring.cloud.tasks.tasks_manager.tasks_manager.service.AllotTaskItemService;

@Slf4j
@Setter
@Getter
public class TasksFullAllotListener extends TreeCacheListener {

    private AllotTaskItemService allotTaskItemService;

    public TasksFullAllotListener(AllotTaskItemService allotTaskService) {
        this.allotTaskItemService = allotTaskService;
    }

    @Override
    public void childEvent(Type type, String path, String nodeData) throws Exception {
        if (isShardAllAtOnce(type, path)) {
            log.info("shard-all-at-once triggered.");
            allotTaskItemService.tasksFullAllot();
        }
    }

    private boolean isShardAllAtOnce(Type type, String path) {
        return type == Type.NODE_ADDED && Node.getExecutorShardingNodePath("shardAllAtOnce").equals(path);
    }

}
